import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Card,
  Row,
  Col,
  type TableColumnsType,
} from '@nbase/ui';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from '@nbase/ui/icons';
import { dictService, dictDataService, type Dict, type DictData, type CreateDictDto, type UpdateDictDto, type CreateDictDataDto, type UpdateDictDataDto, type QueryDictDto, type QueryDictDataDto } from '~/services/dict.service';
import { COMMON_STATUS, CommonStatus, PAGINATION } from '@nbase/shared';
import { formatDateTime, formatStatusLabel, getStatusColor } from '~/utils/format';
import { INPUT_WIDTH, TABLE_COLUMN_WIDTH } from '~/constants';

/**
 * 字典管理页面
 */
const DictManagement: React.FC = () => {
  // 字典列表状态
  const [dictLoading, setDictLoading] = useState(false);
  const [dictDataSource, setDictDataSource] = useState<Dict[]>([]);
  const [dictTotal, setDictTotal] = useState(0);
  const [dictPage, setDictPage] = useState(1);
  const [dictPageSize, setDictPageSize] = useState<number>(PAGINATION.DEFAULT_PAGE_SIZE);
  const [dictSearchForm] = Form.useForm();
  const [dictModalVisible, setDictModalVisible] = useState(false);
  const [dictModalForm] = Form.useForm();
  const [editingDictId, setEditingDictId] = useState<string | null>(null);

  // 字典数据列表状态
  const [selectedDict, setSelectedDict] = useState<Dict | null>(null);
  const [dictDataLoading, setDictDataLoading] = useState(false);
  const [dictDataDataSource, setDictDataDataSource] = useState<DictData[]>([]);
  const [dictDataTotal, setDictDataTotal] = useState(0);
  const [dictDataPage, setDictDataPage] = useState(1);
  const [dictDataPageSize, setDictDataPageSize] = useState<number>(PAGINATION.DEFAULT_PAGE_SIZE);
  const [dictDataModalVisible, setDictDataModalVisible] = useState(false);
  const [dictDataModalForm] = Form.useForm();
  const [editingDictDataId, setEditingDictDataId] = useState<string | null>(null);

  /**
   * 加载字典列表
   */
  const loadDictData = async (params?: QueryDictDto) => {
    try {
      setDictLoading(true);
      const response = await dictService.getList({
        page: dictPage,
        pageSize: dictPageSize,
        ...params,
      });
      setDictDataSource(response.items);
      setDictTotal(response.total);
    } catch {
      // 错误已由 request.ts 统一处理
    } finally {
      setDictLoading(false);
    }
  };

  /**
   * 加载字典数据列表
   */
  const loadDictDataData = async (params?: QueryDictDataDto) => {
    if (!selectedDict) return;

    try {
      setDictDataLoading(true);
      const response = await dictDataService.getList({
        page: dictDataPage,
        pageSize: dictDataPageSize,
        dictId: selectedDict.id,
        ...params,
      });
      setDictDataDataSource(response.items);
      setDictDataTotal(response.total);
    } catch {
      // 错误已由 request.ts 统一处理
    } finally {
      setDictDataLoading(false);
    }
  };

  /**
   * 初始化加载字典列表
   */
  useEffect(() => {
    loadDictData();
  }, [dictPage, dictPageSize]);

  /**
   * 当选中字典变化时，加载字典数据
   */
  useEffect(() => {
    if (selectedDict) {
      loadDictDataData();
    }
  }, [selectedDict, dictDataPage, dictDataPageSize]);

  /**
   * 字典搜索
   */
  const handleDictSearch = () => {
    const values = dictSearchForm.getFieldsValue();
    setDictPage(1);
    loadDictData(values);
  };

  /**
   * 字典重置搜索
   */
  const handleDictReset = () => {
    dictSearchForm.resetFields();
    setDictPage(1);
    loadDictData();
  };

  /**
   * 打开字典新增/编辑弹窗
   */
  const handleOpenDictModal = (record?: Dict) => {
    if (record) {
      setEditingDictId(record.id);
      dictModalForm.setFieldsValue(record);
    } else {
      setEditingDictId(null);
      dictModalForm.resetFields();
    }
    setDictModalVisible(true);
  };

  /**
   * 关闭字典弹窗
   */
  const handleCloseDictModal = () => {
    setDictModalVisible(false);
    setEditingDictId(null);
    dictModalForm.resetFields();
  };

  /**
   * 提交字典表单
   */
  const handleDictSubmit = async () => {
    try {
      const values = await dictModalForm.validateFields();
      if (editingDictId) {
        await dictService.update(editingDictId, values as UpdateDictDto);
        message.success('更新成功');
      } else {
        await dictService.create(values as CreateDictDto);
        message.success('创建成功');
      }
      handleCloseDictModal();
      loadDictData();
    } catch {
      // 表单验证失败或请求失败，错误已由相应模块处理
    }
  };

  /**
   * 删除字典
   */
  const handleDictDelete = async (id: string) => {
    try {
      await dictService.delete(id);
      message.success('删除成功');
      loadDictData();
      if (selectedDict?.id === id) {
        setSelectedDict(null);
      }
    } catch {
      // 错误已由 request.ts 统一处理
    }
  };

  /**
   * 打开字典数据新增/编辑弹窗
   */
  const handleOpenDictDataModal = (record?: DictData) => {
    if (record) {
      setEditingDictDataId(record.id);
      dictDataModalForm.setFieldsValue(record);
    } else {
      setEditingDictDataId(null);
      dictDataModalForm.resetFields();
      dictDataModalForm.setFieldValue('dictId', selectedDict?.id);
    }
    setDictDataModalVisible(true);
  };

  /**
   * 关闭字典数据弹窗
   */
  const handleCloseDictDataModal = () => {
    setDictDataModalVisible(false);
    setEditingDictDataId(null);
    dictDataModalForm.resetFields();
  };

  /**
   * 提交字典数据表单
   */
  const handleDictDataSubmit = async () => {
    try {
      const values = await dictDataModalForm.validateFields();
      if (editingDictDataId) {
        await dictDataService.update(editingDictDataId, values as UpdateDictDataDto);
        message.success('更新成功');
      } else {
        await dictDataService.create(values as CreateDictDataDto);
        message.success('创建成功');
      }
      handleCloseDictDataModal();
      loadDictDataData();
    } catch {
      // 表单验证失败或请求失败，错误已由相应模块处理
    }
  };

  /**
   * 删除字典数据
   */
  const handleDictDataDelete = async (id: string) => {
    try {
      await dictDataService.delete(id);
      message.success('删除成功');
      loadDictDataData();
    } catch {
      // 错误已由 request.ts 统一处理
    }
  };

  /**
   * 字典表格列定义
   */
  const dictColumns: TableColumnsType<Dict> = [
    {
      title: '字典名称',
      dataIndex: 'name',
      key: 'name',
      width: TABLE_COLUMN_WIDTH.DESCRIPTION,
    },
    {
      title: '字典编码',
      dataIndex: 'code',
      key: 'code',
      width: TABLE_COLUMN_WIDTH.DESCRIPTION,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: TABLE_COLUMN_WIDTH.STATUS,
      render: (status: number) => (
        <Tag color={getStatusColor(status as CommonStatus)}>{formatStatusLabel(status as CommonStatus)}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: TABLE_COLUMN_WIDTH.DATETIME,
      render: (text: string) => formatDateTime(text),
    },
    {
      title: '操作',
      key: 'action',
      width: TABLE_COLUMN_WIDTH.PATH,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => setSelectedDict(record)}
          >
            数据
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleOpenDictModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDictDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  /**
   * 字典数据表格列定义
   */
  const dictDataColumns: TableColumnsType<DictData> = [
    {
      title: '标签',
      dataIndex: 'label',
      key: 'label',
      width: TABLE_COLUMN_WIDTH.DESCRIPTION,
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
      width: TABLE_COLUMN_WIDTH.DESCRIPTION,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: TABLE_COLUMN_WIDTH.STATUS,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: TABLE_COLUMN_WIDTH.STATUS,
      render: (status: number) => (
        <Tag color={getStatusColor(status as CommonStatus)}>{formatStatusLabel(status as CommonStatus)}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: TABLE_COLUMN_WIDTH.ACTIONS,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleOpenDictDataModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDictDataDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Row gutter={16}>
        {/* 左侧：字典列表 */}
        <Col span={12}>
          <Card title="字典列表">
            {/* 搜索表单 */}
            <Form form={dictSearchForm} layout="inline" style={{ marginBottom: 16 }}>
              <Form.Item name="name" label="字典名称">
                <Input placeholder="请输入字典名称" allowClear style={{ width: INPUT_WIDTH.MD }} />
              </Form.Item>
              <Form.Item name="code" label="字典编码">
                <Input placeholder="请输入字典编码" allowClear style={{ width: INPUT_WIDTH.MD }} />
              </Form.Item>
              <Form.Item name="status" label="状态">
                <Select placeholder="请选择状态" allowClear style={{ width: INPUT_WIDTH.MD }}>
                  <Select.Option value={COMMON_STATUS.ACTIVE}>启用</Select.Option>
                  <Select.Option value={COMMON_STATUS.DISABLED}>禁用</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" icon={<SearchOutlined />} onClick={handleDictSearch}>
                    搜索
                  </Button>
                  <Button onClick={handleDictReset}>重置</Button>
                </Space>
              </Form.Item>
            </Form>

            {/* 操作按钮 */}
            <div style={{ marginBottom: 16 }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => handleOpenDictModal()}>
                新增字典
              </Button>
            </div>

            {/* 表格 */}
            <Table
              columns={dictColumns}
              dataSource={dictDataSource}
              rowKey="id"
              loading={dictLoading}
              pagination={{
                current: dictPage,
                pageSize: dictPageSize,
                total: dictTotal,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
                pageSizeOptions: PAGINATION.PAGE_SIZE_OPTIONS.map(String),
                onChange: (page, pageSize) => {
                  setDictPage(page);
                  setDictPageSize(pageSize);
                },
              }}
              scroll={{ x: 800 }}
            />
          </Card>
        </Col>

        {/* 右侧：字典数据列表 */}
        <Col span={12}>
          <Card title={selectedDict ? `字典数据 - ${selectedDict.name}` : '字典数据'}>
            {selectedDict ? (
              <>
                {/* 操作按钮 */}
                <div style={{ marginBottom: 16 }}>
                  <Button type="primary" icon={<PlusOutlined />} onClick={() => handleOpenDictDataModal()}>
                    新增数据
                  </Button>
                </div>

                {/* 表格 */}
                <Table
                  columns={dictDataColumns}
                  dataSource={dictDataDataSource}
                  rowKey="id"
                  loading={dictDataLoading}
                  pagination={{
                    current: dictDataPage,
                    pageSize: dictDataPageSize,
                    total: dictDataTotal,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 条`,
                    pageSizeOptions: PAGINATION.PAGE_SIZE_OPTIONS.map(String),
                    onChange: (page, pageSize) => {
                      setDictDataPage(page);
                      setDictDataPageSize(pageSize);
                    },
                  }}
                  scroll={{ x: 600 }}
                />
              </>
            ) : (
              <div style={{ textAlign: 'center', padding: '50px', color: '#999' }}>
                请先选择一个字典
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 字典新增/编辑弹窗 */}
      <Modal
        title={editingDictId ? '编辑字典' : '新增字典'}
        open={dictModalVisible}
        onOk={handleDictSubmit}
        onCancel={handleCloseDictModal}
        width={600}
      >
        <Form form={dictModalForm} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
          <Form.Item
            name="name"
            label="字典名称"
            rules={[{ required: true, message: '请输入字典名称' }]}
          >
            <Input placeholder="请输入字典名称" />
          </Form.Item>
          <Form.Item
            name="code"
            label="字典编码"
            rules={[{ required: true, message: '请输入字典编码' }]}
          >
            <Input placeholder="请输入字典编码" disabled={!!editingDictId} />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>
          <Form.Item name="status" label="状态" initialValue={COMMON_STATUS.ACTIVE}>
            <Select>
              <Select.Option value={COMMON_STATUS.ACTIVE}>启用</Select.Option>
              <Select.Option value={COMMON_STATUS.DISABLED}>禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 字典数据新增/编辑弹窗 */}
      <Modal
        title={editingDictDataId ? '编辑字典数据' : '新增字典数据'}
        open={dictDataModalVisible}
        onOk={handleDictDataSubmit}
        onCancel={handleCloseDictDataModal}
        width={600}
      >
        <Form form={dictDataModalForm} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
          <Form.Item name="dictId" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            name="label"
            label="标签"
            rules={[{ required: true, message: '请输入标签' }]}
          >
            <Input placeholder="请输入标签" />
          </Form.Item>
          <Form.Item
            name="value"
            label="值"
            rules={[{ required: true, message: '请输入值' }]}
          >
            <Input placeholder="请输入值" />
          </Form.Item>
          <Form.Item name="sort" label="排序" initialValue={0}>
            <Input placeholder="请输入排序" />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>
          <Form.Item name="status" label="状态" initialValue={COMMON_STATUS.ACTIVE}>
            <Select>
              <Select.Option value={COMMON_STATUS.ACTIVE}>启用</Select.Option>
              <Select.Option value={COMMON_STATUS.DISABLED}>禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DictManagement;

